package com.gegewa.topic.file.service.impl;

import com.gegewa.topic.file.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service("fileService")
public class FileServiceImpl implements FileService {

    @Override
    public List<String> uploadFile(HttpServletRequest request, String directoryPath) throws IOException {
        if (!(request instanceof MultipartHttpServletRequest)) {
            throw new IllegalArgumentException("request must instanceof MultipartHttpServletRequest");
        }
        if (!directoryPath.endsWith(File.separator)) {
            directoryPath += File.separator;
        }
        List<String> fileSavePathList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
        if (!fileNames.hasNext()) {
            throw new IllegalArgumentException("file not exists");
        }
        while(fileNames.hasNext()) {
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(fileNames.next());
            String filename = multipartFile.getOriginalFilename();
            saveFile(multipartFile, directoryPath, filename);
            fileSavePathList.add(directoryPath + filename);
        }
        return fileSavePathList;
    }

    private void saveFile(MultipartFile multipartFile, String directoryPath, String filename) throws IOException {
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new RuntimeException("file not exists");
        }
        createDirectoryIfNotExists(directoryPath);
        if (!directoryPath.endsWith(File.separator)) {
            directoryPath += File.separator;
        }
        multipartFile.transferTo(new File(directoryPath + filename));
    }

    @Override
    public void createDirectoryIfNotExists(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists() && !directory.isDirectory()) {
            directory.mkdirs();
        }
    }

}
